package me.xplabs.model
{
	import flash.geom.Point;
	import flash.utils.Dictionary;
	import me.xplabs.constant.GridType;
	import me.xplabs.Globals;
	import me.xplabs.model.combatunit.MRoleInfo;
	
	/**
	 * http://www.xplabs.me/
	 * @author xiaohan
	 */
	public class RolePositionManager
	{
		private static var _instance:RolePositionManager;
		public var paths:Dictionary;
		public var grids:Vector.<Vector.<int>>;
		
		public function RolePositionManager()
		{
			paths = new Dictionary();
		}
		
		public static function get i():RolePositionManager
		{
			return _instance ||= new RolePositionManager();
		}
		
		/**
		 * 设置格子中的敌人引用
		 * @param	p_actor
		 */
		public function setCellActor(p_actor:MRoleInfo):void
		{
			if (!p_actor.prevCellPos.equals(p_actor.curCellPos))
			{
				deleteCellActor(p_actor.prevCellPos, p_actor.curCellPos, p_actor.soleId);
				var temp:Vector.<MRoleInfo> = paths[p_actor.curCellPos.x + "-" + p_actor.curCellPos.y];
				if (!temp)
				{
					temp = new Vector.<MRoleInfo>();
					paths[p_actor.curCellPos.x + "-" + p_actor.curCellPos.y] = temp;
				}
				temp.push(p_actor);
			}
		}
		
		/**
		 * 删除格子的角色引用
		 * @param	p_point
		 * @param	p_soleId
		 */
		public function deleteCellActor(p_point:Point, c_point:Point, p_soleId:int):void
		{
			var temp:Vector.<MRoleInfo> = paths[p_point.x + "-" + p_point.y];
			if (temp)
			{
				var len:int = temp.length;
				for (var i:int = 0; i < len; i++)
				{
					if (p_soleId == temp[i].soleId)
					{
						temp.splice(i, 1);
						return;
					}
				}
			}
			temp = paths[c_point.x + "-" + c_point.y];
			if (temp)
			{
				len = temp.length;
				for (i = 0; i < len; i++)
				{
					if (p_soleId == temp[i].soleId)
					{
						temp.splice(i, 1);
						return;
					}
				}
			}
		}
		
		public function dipose():void
		{
			for (var name:String in paths)
			{
				if (paths[name])
					paths[name].length = 0;
				delete paths[name];
			}
		}
		
		public function checkObstruct(px:Number, py:Number):Boolean
		{
			var cellX:int = px / Globals.cellW;
			var cellY:int = py / Globals.cellH;
			return grids[cellX][cellY] == GridType.ABLE;
		}
	}

}